<template>
  <div
    class="training-detail"
    :style="{ height: $store.oj.systemParams.screenHeight * 0.7 + 'px' }"
  >
    <el-tabs v-model="tabPosition">
      <el-tab-pane name="first">
        <template #label>
          <span class="tab-title">
            <i class="iconfont icon-gongsijianjie"></i>
            <span>训练简介</span>
          </span>
        </template>
        <div class="pane">
          <div
            class="p-header"
            :style="{
              height: $store.oj.systemParams.screenHeight * 0.3 + 'px',
            }"
          >
            <div class="introduction">
              <div class="row">
                <div class="r-title">训练编号</div>
                <div class="r-contain">{{ trainingDetail.id }}</div>
              </div>
              <div class="row">
                <div class="r-title">训练名称</div>
                <div class="r-contain">{{ trainingDetail.title }}</div>
              </div>
              <div class="row">
                <div class="r-title">训练权限</div>
                <div class="r-contain">
                  <n-tag
                    type="error"
                    v-show="trainingDetail.auth == 1"
                    round
                    size="small"
                    :bordered="false"
                    >私有训练</n-tag
                  >
                  <n-tag
                    type="success"
                    v-show="trainingDetail.auth == 0"
                    round
                    size="small"
                    :bordered="false"
                    >公开训练</n-tag
                  >
                  <n-tag
                    type="warning"
                    v-show="trainingDetail.auth == 2"
                    round
                    size="small"
                    :bordered="false"
                    >保护训练</n-tag
                  >
                </div>
              </div>
              <div class="row">
                <div class="r-title">训练分类</div>
                <div class="r-contain">
                  <n-tag
                    round
                    size="small"
                    :color="{
                      color: trainingDetail.categoryColor,
                      borderColor: trainingDetail.categoryColor,
                      textColor: '#fff',
                    }"
                    >{{ trainingDetail.categoryName }}</n-tag
                  >
                </div>
              </div>
              <div class="row">
                <div class="r-title">总题数</div>
                <div class="r-contain">{{ trainingDetail.problemCount }}</div>
              </div>
              <div class="row">
                <div class="r-title">作者</div>
                <div class="r-contain">{{ trainingDetail.author }}</div>
              </div>
              <div class="row">
                <div class="r-title">最近更新</div>
                <div class="r-contain">{{ trainingDetail.updateTime }}</div>
              </div>
            </div>
            <div class="description">
              <div class="d-title">训练简介</div>
              <v-md-editor
                class="d-container"
                :mode="'preview'"
                v-model="trainingDetail.description"
              >
              </v-md-editor>
            </div>
          </div>

          <transition>
            <div
              class="progress"
              :style="{
                height: $store.oj.systemParams.screenHeight * 0.32 + 'px',
              }"
              v-if="isNeedPasswd"
            >
              <div class="p-title">训练进度</div>
              <n-progress
                class="n-progress"
                type="line"
                :height="15"
                :percentage="
                  getPercent(
                    trainingDetail.acCount,
                    trainingDetail.problemCount
                  )
                "
                processing
              />
              <div class="p-text">
                {{ trainingDetail.acCount }} / {{ trainingDetail.problemCount }}
              </div>
            </div>
          </transition>

          <transition>
            <div
              class="passwd"
              v-if="!isNeedPasswd && trainingDetail.auth == 1"
            >
              <div class="p-tip">
                <i class="iconfont icon-guanyu"></i> 私有训练密码
              </div>
              <div class="p-input">
                <n-input
                  class="p-i-input"
                  placeholder="训练密码"
                  type="password"
                  clearable
                  show-password-on="mousedown"
                  :status="passwdStatus"
                  v-model:value="privatePasswd"
                  @blur="updatePasswdStatus"
                ></n-input>
                <n-button class="p-i-btn" type="success" @click="trainingPasswd"
                  >确认</n-button
                >
              </div>
            </div>
          </transition>
          <transition>
            <div
              class="passwd"
              v-if="!isNeedPasswd && trainingDetail.auth == 2"
            >
              <n-button strong secondary type="error" round class="protect"
                ><i class="iconfont icon-guanyu"></i>
                保护训练仅对特定用户开放</n-button
              >
            </div>
          </transition>
        </div>
      </el-tab-pane>
      <el-tab-pane name="second" v-if="isNeedPasswd">
        <template #label>
          <span class="tab-title">
            <i class="iconfont icon-liebiao_o"></i>
            <span>训练题单</span>
          </span>
        </template>
        <div
          class="pane2"
          :style="{ height: $store.oj.systemParams.screenHeight * 0.65 + 'px' }"
        >
          <el-table :data="trainingProblem.records" stripe class="problemTable">
            <el-table-column width="40px" align="center">
              <template #default="scoped">
                <div
                  class="status"
                  v-show="problemStatusList[scoped.row.id] != undefined"
                >
                  <i
                    class="iconfont icon-gou ac"
                    v-if="problemStatusList[scoped.row.id] == 'Accepted'"
                  ></i>
                  <i
                    class="iconfont icon-henggang se"
                    v-else-if="
                      problemStatusList[scoped.row.id] == 'System Error'
                    "
                  ></i>
                  <i
                    class="iconfont icon-henggang blue"
                    v-else-if="
                      problemStatusList[scoped.row.id] == 'Partial Accepted'
                    "
                  ></i>
                  <i
                    class="iconfont icon-henggang orange"
                    v-else-if="
                      problemStatusList[scoped.row.id] ==
                        'Presentation Error' ||
                      problemStatusList[scoped.row.id] == 'Compile Error'
                    "
                  ></i>
                  <i class="iconfont icon-chahao1 red" v-else></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="problemId" label="题目ID" />
            <el-table-column prop="title" label="题目">
              <template #default="scoped">
                <div
                  class="problemTable-title"
                  @click="hanlderToProbDetail(scoped.row.id)"
                >
                  {{ scoped.row.title }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="difficulty" label="难度" align="center">
              <template #default="scoped">
                <el-tag
                  round
                  size="small"
                  type="success"
                  v-show="scoped.row.difficulty === 0"
                  >简单</el-tag
                >
                <el-tag
                  round
                  size="small"
                  type="warning"
                  v-show="scoped.row.difficulty === 1"
                  >中等</el-tag
                >
                <el-tag
                  round
                  size="small"
                  type="danger"
                  v-show="scoped.row.difficulty === 2"
                  >困难</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="标签">
              <template #default="scoped">
                <n-tag
                  class="title-tag"
                  size="small"
                  v-for="item in scoped.row.tagList"
                  :key="item.id"
                  :color="{ textColor: item.color, borderColor: item.color }"
                >
                  {{ item.name }}
                </n-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ioScore" label="分数" align="center" />
          </el-table>
          <div class="pagenition">
            <el-pagination
              class="pagination"
              :page-sizes="[10, 20, 30]"
              background
              small
              layout="prev, pager, next,sizes"
              :total="Number(trainingProblem.total)"
              v-model:current-page="searchParams.pageNum"
              v-model:page-size="searchParams.pageSize"
            />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="three" v-if="checkPermission">
        <template #label>
          <span class="tab-title" @click="getPersonStatus">
            <i class="iconfont icon-liebiao1"></i>
            <span>完成情况</span>
          </span>
        </template>
        <div
          class="pane2"
          :style="{ height: $store.oj.systemParams.screenHeight * 0.75 + 'px' }"
        >
          <div class="p-head">
            <n-input
              class="search-input"
              placeholder="搜索"
              round
              size="small"
              v-model:value="searchKey.keyword"
              @change="searchUser"
            >
              <template #suffix>
                <i class="iconfont icon-sousuo"></i>
              </template>
            </n-input>
            <div class="flash">
              <n-button type="primary" size="small" round @click="falshRank">
                <template #icon>
                  <i class="iconfont icon-shuaxin"></i>
                </template>
                刷新
              </n-button>
            </div>
          </div>
          <el-table :data="userData.records" stripe class="userTable">
            <el-table-column label="用户" width="200px" align="center">
              <template #default="scope">
                <div class="avatar-box">
                  <el-avatar
                    class="avatar"
                    :src="$getAvatarUrl(scope.row.avatar)"
                  >
                    <i class="iconfont icon-zhanghao-"></i>
                  </el-avatar>
                  <div class="avatar-username">
                    {{ scope.row?.username || "--" }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="真实姓名" align="center">
              <template #default="scope">
                <div class="nickname">
                  {{ scope.row.realName || "--" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="分数"
              prop="score"
              align="center"
            ></el-table-column>
            <el-table-column label="通过/尝试数/总数" align="center">
              <template #default="scope">
                <div>
                  {{ scope.row.acProblemTotal }}/{{ scope.row.problemTotal }}/{{
                    trainingProblem.total
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="通过率" align="center">
              <template #default="scope">
                <n-tooltip trigger="hover">
                  <template #trigger>
                    <div class="ACrate">
                      {{
                        getACRate(scope.row.acJudgeTotal, scope.row.judgeTotal)
                      }}
                    </div>
                  </template>
                  <div>
                    {{ scope.row.acJudgeTotal }}/{{ scope.row.judgeTotal }}
                  </div>
                </n-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="ioScore" label="完成度" align="center">
              <template #default="scoped">
                <n-tooltip
                  trigger="hover"
                  style="background-color: #fff; color: #000"
                >
                  <template #trigger>
                    <div>
                      <n-progress
                        type="line"
                        indicator-placement="inside"
                        :percentage="
                          getPercent(
                            parseInt(scoped.row.acProblemTotal),
                            parseInt(trainingProblem.total)
                          )
                        "
                        color="rgb(105,187,98)"
                        indicator-text-color="black"
                      ></n-progress>
                    </div>
                  </template>
                  <div class="person-head">完成度</div>
                  <div
                    class="problemAnswerInfo"
                    @click="toEvaluation(scoped.row.submitInfo[item.id])"
                    v-for="item in problemStatus(totalProblem.records)"
                  >
                    <div class="id">{{ item.title }}:</div>
                    <div
                      class="score"
                      v-if="scoped.row.submissionInfo[item.id]"
                      :class="{
                        zero:
                          scoped.row.statusInfo[item.id] !== 0 ||
                          scoped.row.statusInfo[item.id] !== 1,
                        part: scoped.row.statusInfo[item.id] === 1,
                        full: scoped.row.statusInfo[item.id] === 0,
                      }"
                    >
                      {{ scoped.row.submissionInfo[item.id] }}
                    </div>
                    <div class="score" v-else>------</div>
                  </div>
                </n-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagenition">
            <el-pagination
              class="pagination"
              :page-sizes="[10, 20, 30]"
              background
              small
              layout="prev, pager, next,sizes"
              :page-count="Number(userData.total)"
              v-model:current-page="searchKey.pageNum"
              v-model:page-size="searchKey.pageSize"
              @change="changePage"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  getTrainingDetailAPI,
  getTrainingProblemListAPI,
  getTrainingAuthAPI,
  trainingPasswdAPI,
  getProblemStatusAPI,
} from "@/api/ojAPI/ojAPI";
import { getTrainIngListAPI } from "@/api/adminAPI/adminAPI";
import { ElMessage } from "element-plus";

export default {
  data() {
    return {
      tabPosition: "first",
      searchParams: {
        pageNum: 1,
        pageSize: 10,
        tid: -1,
      },
      trainingDetail: {},
      trainingProblem: {
        records: [],
        total: 10,
      },
      isNeedPasswd: false,
      privatePasswd: "",
      passwdStatus: "",
      timer: null,
      problemStatusList: {},
      toolbar: "",
      searchKey: {
        pageNum: 1,
        pageSize: 10,
        tid: -1,
        keyword: "",
      },
      userData: {
        records: [],
        total: 1,
      },
      totalProblem: {
        records: [],
        total: 10,
      },
      time: null,
    };
  },
  mounted() {
    this.getTrainingDetail();
    this.searchParams.tid = this.$route.params.tid;
    this.searchKey.tid = this.$route.params.tid;
    this.getTrainingAuth(this.searchParams.tid);
    this.getTrainingProblemList(true);
  },
  methods: {
    //获取训练详情
    async getTrainingDetail() {
      await getTrainingDetailAPI(this.$route.params.tid)
        .then((res) => {
          if (res.data.code === 200) {
            this.trainingDetail = res.data.data;
          }
        })
        .catch((err) => {
          console.log("系统错误");
        });
    },
    //获取题单列表
    async getTrainingProblemList(isToal) {
      if (isToal) {
        this.searchParams.pageSize = 9999;
      }
      await getTrainingProblemListAPI(this.searchParams)
        .then((res) => {
          if (res.data.code === 200) {
            const arr = [];
            if (res.data.data != null)
              if (isToal) {
                this.totalProblem = res.data.data;
                this.searchParams.pageSize = 10;
              } else {
                this.trainingProblem = res.data.data;
                this.trainingProblem.records.forEach((ele) => {
                  arr.push(ele.id);
                });
                this.getProblemStatus(arr);
              }
          }
        })
        .catch((err) => {
          console.log("系统错误");
        });
    },
    //获取用户通过率百分比
    getACRate(actotal, total) {
      if (total === 0 || actotal === 0) {
        return "0%";
      }
      return ((actotal / total) * 100).toFixed(2) + "%";
    },
    //对用户作答过的题目进行总结
    problemStatus(probelm) {
      const arr = [];
      this.totalProblem.records.forEach((item) => {
        arr.push({
          id: item.id,
          title: item.title,
        });
      });
      return arr;
    },
    //刷新
    falshRank() {
      if (this.time) {
        clearTimeout(this.time);
      }
      this.time = setTimeout(() => {
        this.getPersonStatus();
      }, 300);
    },
    //路由跳转
    hanlderToProbDetail(id) {
      this.isQuiz = true;
      this.$router.push({
        path: `/home/bank/${id}`,
      });
    },
    //获取通过率
    getPercent(acCount, problemCount) {
      if (problemCount == 0) {
        return 0;
      }
      return Number(
        ((((acCount * 100) / problemCount) * 100) / 100).toFixed(2)
      );
    },
    //去往评测
    toEvaluation(id) {
      if (id) {
        this.$router.push({
          path: `/home/evaluation-detail/${id}`,
        });
      } else {
        ElMessage.error("未作答无法查看");
        return;
      }
    },
    changePage() {
      this.getPersonStatus();
    },
    searchUser() {
      if (this.time) {
        clearTimeout(this.time);
        this.time = null;
      }
      this.time = setTimeout(() => {
        this.searchKey.pageNum = 1;
        this.getPersonStatus();
      }, 300);
    },
    //获取权限
    async getTrainingAuth(id) {
      await getTrainingAuthAPI(id)
        .then((res) => {
          if (res.data.code === 200) {
            this.isNeedPasswd = res.data.data;
          }
        })
        .catch((err) => {
          console.log("系统错误");
        });
    },
    //校验训练密码
    async trainingPasswd() {
      if (this.privatePasswd.length <= 0) {
        this.passwdStatus = "error";
        ElMessage.error("请输入训练密码");
        return;
      }
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = await setTimeout(() => {
        trainingPasswdAPI(this.searchParams.tid, this.privatePasswd)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.msg);
              this.getTrainingAuth(this.searchParams.tid);
            }
          })
          .catch((err) => {
            console.log("系统错误");
          });
      }, 1000);
    },
    updatePasswdStatus() {
      if (this.privatePasswd.length > 0) {
        this.passwdStatus = "";
      } else {
        this.passwdStatus = "error";
      }
    },
    //获取用户对题目的答题状态
    async getProblemStatus(ids) {
      if (!this.$store.oj.isLogin) {
        return;
      }
      await getProblemStatusAPI(ids)
        .then((res) => {
          if (res.data.code === 200) {
            this.problemStatusList = res.data.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取用户的完成情况
    async getPersonStatus() {
      await getTrainIngListAPI(this.searchKey).then((res) => {
        if (res.data === "") {
          return;
        }
        this.userData = res.data.data;
      });
    },
  },
  watch: {
    searchParams: {
      deep: true,
      handler() {
        if (this.searchParams.pageSize === 9999) {
          return;
        }
        this.getTrainingProblemList();
      },
    },
    searchKey: {
      deep: true,
      handler() {
        if (this.$store.oj.userData.authLevel > 0) {
          if (this.time) {
            clearTimeout(this.time);
          }
          this.time = setTimeout(() => {
            this.getPersonStatus();
          }, 200);
        }
      },
    },
  },
  computed: {
    checkPermission() {
      return (
        this.$store?.oj?.getPermission?.find((item) => {
          return item?.includes("manage:train:select");
        }) || this.$store?.oj?.userData?.username == this.trainingDetail.author
      );
    },
  },
};
</script>

<style lang="less" scoped>
.training-detail {
  width: 95%;
  padding-top: 10px;
  margin: 0 auto;
  border-radius: 16px;
  padding: 10px;

  .pane {
    .p-header {
      display: flex;

      .introduction {
        border-radius: 10px;
        padding: 0 20px;
        width: 25%;
        height: 100%;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        margin: 0 auto;
        box-shadow: 5px 5px 16px #e6e6e6, -5px -5px 16px #ffffff;

        .row {
          display: flex;
          justify-content: space-between;

          .r-contain {
            color: #888;
          }
        }
      }

      .description {
        border-radius: 10px;
        height: 100%;
        width: 70%;
        background-color: #fff;
        margin: 0 auto;
        box-shadow: 5px 5px 20px #e8e8e8, -5px -5px 20px #ffffff;
        overflow: hidden;

        .d-title {
          font-size: 18px;
          font-weight: 550;
          margin: 10px;
        }

        .d-container {
          margin: 0 10px;
        }
      }
    }
  }

  .pane2 {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 20px;
    box-shadow: 5px 5px 20px #e8e8e8, -5px -5px 20px #ffffff;

    .problemTable {
      width: 100%;
      height: 93%;

      .status {
        display: flex;
        justify-content: center;

        .ac {
          color: rgb(58, 159, 85);
        }

        .se {
          color: grey;
        }

        .red {
          color: rgb(228, 103, 102);
        }

        .blue {
          color: rgb(85, 158, 255);
        }

        .orange {
          color: orange;
        }
      }

      .problemTable-title:hover {
        color: rgb(85, 158, 255);
        cursor: pointer;
        text-decoration: underline;
      }
    }

    .userTable {
      height: 70vh;

      .avatar-box {
        display: flex;
        justify-content: left;
        height: 30px;
        padding-left: 10px;

        .avatar {
          height: 30px;
          width: 30px;
          margin: auto 5px auto 0;
        }

        .avatar-username {
          color: #888;
          font-size: 14px;
          margin: auto 5px;
        }
      }

      .nickname {
        display: flex;
        justify-content: center;

        .img {
          width: 22px;
          height: 22px;
          margin: auto 3px;
        }
      }

      .ACrate {
        font-size: 14px;
      }

      .signature {
        max-width: 400px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .p-head {
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 35px;
      padding-top: 10px;

      .search-input {
        width: 20%;
        margin: auto 3% auto 3%;
      }

      .flash {
        margin-right: 10px;
      }
    }

    .pagenition {
      height: 7%;
      margin: auto auto 0 auto;
      display: flex;
      justify-content: center;
    }
  }

  .progress {
    display: flex;
    flex-direction: column;
    width: 99%;
    background-color: #fff;
    border-radius: 20px;
    box-shadow: 5px 5px 20px #e8e8e8, -5px -5px 20px #ffffff;
    margin: 20px auto;

    .p-title {
      font-size: 18px;
      font-weight: 550;
      margin: 15px 0 0 15px;
    }

    .n-progress {
      width: 90%;
      height: 40px;
      margin: auto auto 0 auto;
    }

    .p-text {
      margin: 0 auto auto auto;
      font-size: 18px;
      font-weight: 550;
    }
  }

  .passwd {
    width: 60%;
    padding: 10px;
    background-color: #fff;
    border-radius: 20px;
    margin: 20px auto;
    height: 35vh;
    display: flex;
    flex-direction: column;

    .p-tip {
      color: rgb(223, 162, 56);
      text-align: center;
      height: 20%;
      font-size: 20px;
      font-weight: 550;
    }

    .p-input {
      height: 50%;
      display: flex;

      .p-i-input {
        width: 40%;
        margin: auto 0 auto auto;
      }

      .p-i-btn {
        width: 7%;
        margin: auto auto auto 10px;
      }
    }

    .protect {
      margin: auto;
      font-size: 24px;
      width: 80%;
      height: 20%;

      .iconfont {
        font-size: 28px;
      }
    }
  }
}

::v-deep(.el-tabs__nav-scroll) {
  background-color: #fff;
  padding: 0 10px;
  border-radius: 5px;
  box-shadow: 5px 5px 20px #e8e8e8, -5px -5px 20px #ffffff;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.person-head {
  font-size: 1.0765rem;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 550;
}

.problemAnswerInfo {
  padding: 2px 3px;
  display: flex;
  font-weight: 400;
  justify-content: left;
  align-items: center;

  .id {
    margin-right: 3px;
  }
}

.problemAnswerInfo:hover {
  cursor: pointer;
  text-decoration: underline;
  color: #18a058;
}

.zero {
  color: rgba(228, 31, 31, 0.83);
  font-weight: 400;
}

.part {
  color: #0c61c9a1;
}

.full {
  color: #18a058 !important;
}
</style>
